package com.dataset.manager.service.impl;

import com.dataset.manager.config.StorageConfig;
import com.dataset.manager.config.SystemConfig;
import com.dataset.manager.model.Dataset;
import com.dataset.manager.service.DatasetService;
import com.dataset.manager.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

@Service
public class DatasetServiceImpl implements DatasetService {
    
    private List<Dataset> datasets = new ArrayList<>();
    
    @Autowired
    private SystemConfig systemConfig;
    
    @Autowired
    private StorageService storageService;
    
    @Autowired
    private StorageConfig storageConfig;
    
    @PostConstruct
    public void init() {
        // 初始化存储服务
        storageService.init();
        
        // 初始化一些示例数据
        Dataset sampleDataset = new Dataset();
        sampleDataset.setId("1");
        sampleDataset.setName("Sample Dataset");
        sampleDataset.setDescription("This is a sample dataset");
        sampleDataset.setStatus(Dataset.Status.COMPLETED);
        sampleDataset.setCreatedAt(LocalDateTime.now());
        sampleDataset.setUpdatedAt(LocalDateTime.now());
        sampleDataset.setProgress(100);
        datasets.add(sampleDataset);
    }
    
    @Override
    public CompletableFuture<Dataset> createDataset(String name, String description, String sourceType, String sourcePath) {
        Dataset dataset = new Dataset();
        String id = UUID.randomUUID().toString();
        dataset.setId(id);
        dataset.setName(name);
        dataset.setDescription(description);
        dataset.setStatus(Dataset.Status.PENDING);
        dataset.setCreatedAt(LocalDateTime.now());
        dataset.setUpdatedAt(LocalDateTime.now());
        dataset.setProgress(0);
        dataset.setSourceType(sourceType);
        dataset.setSourcePath(sourcePath);
        
        // 当sourcePath不为空时，根据配置的存储类型复制数据到任务目录
        if (sourcePath != null && !sourcePath.isEmpty()) {
            try {
                // 获取适合当前存储类型的存储服务
                StorageService currentStorageService = storageService.getStorageService(storageConfig.getStorageType());
                
                // 复制数据到任务名目录（使用数据集名称作为任务名）
                String targetPath = currentStorageService.copyDataToTaskDirectory(sourcePath, id);
                
                System.out.println("数据复制成功：从 " + sourcePath + " 到 " + targetPath);
                
                // 设置目标路径
                dataset.setTargetPath(targetPath);
            } catch (Exception e) {
                System.err.println("数据复制失败：" + e.getMessage());
                e.printStackTrace();
                dataset.setStatus(Dataset.Status.FAILED);
                dataset.setDescription(dataset.getDescription() + " (数据复制失败: " + e.getMessage() + ")");
            }
        }
        
        // 将数据集添加到列表中，确保在列表中可见
        datasets.add(dataset);
        
        // 模拟异步处理过程
        CompletableFuture<Dataset> future = CompletableFuture.supplyAsync(() -> {
            try {
                // 更新状态为处理中
                dataset.setStatus(Dataset.Status.PROCESSING);
                dataset.setUpdatedAt(LocalDateTime.now());
                
                // 模拟处理过程中的进度更新
                for (int i = 1; i <= 10; i++) {
                    Thread.sleep(500); // 模拟处理时间
                    dataset.setProgress(i * 10);
                    dataset.setUpdatedAt(LocalDateTime.now());
                }
                
                dataset.setStatus(Dataset.Status.COMPLETED);
                dataset.setUpdatedAt(LocalDateTime.now());
                return dataset;
            } catch (InterruptedException e) {
                dataset.setStatus(Dataset.Status.FAILED);
                dataset.setUpdatedAt(LocalDateTime.now());
                Thread.currentThread().interrupt();
                return dataset;
            }
        });
        
        return future;
    }
    
    @Override
    public boolean deleteDataset(String id) {
        return datasets.removeIf(dataset -> dataset.getId().equals(id));
    }
    
    @Override
    public List<Dataset> listDatasets() {
        return new ArrayList<>(datasets);
    }
    
    @Override
    public Dataset getDatasetById(String id) {
        return datasets.stream()
                .filter(dataset -> dataset.getId().equals(id))
                .findFirst()
                .orElse(null);
    }
}